package com.lenovo.smarttraffic.ui.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.CarErrorResultInfo;
import com.lenovo.smarttraffic.bean.CarErrorResultInfo2;
import com.lenovo.smarttraffic.bean.Data1;
import com.lenovo.smarttraffic.bean.Data2;
import com.lenovo.smarttraffic.bean.LeftData;
import com.lenovo.smarttraffic.bean.RightData;
import com.lenovo.smarttraffic.database.dao.CarErrorResultDatabase;

import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class CarErrorResultActivity extends BaseActivity {

    private String carNumber;
    private List<Data1> data1List;
    private CarErrorResultDatabase carErrorResultDatabase;
    private ListView leftListView;
    private ListView rightListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //自定义标题栏
        initToolBar(findViewById(R.id.toolbar), true,"查询结果");
        //接收传递过来的车牌号
        Intent intent = getIntent();
        carNumber = intent.getStringExtra("carnumber");
        //创建数据库
        carErrorResultDatabase = new CarErrorResultDatabase(this, "CarError.db", null, 1);
        carErrorResultDatabase.getWritableDatabase();
        //解析数据
        sendData1();
        //点击添加车辆按钮事件
        ImageView addImageView = findViewById(R.id.car_error_addbutton);
        addImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent1 = new Intent(CarErrorResultActivity.this, CarErrorActivity.class);
                startActivity(intent1);
            }
        });
        //右边ListView的点击事件
        leftListView = findViewById(R.id.car_error_left_listView);
        rightListView = findViewById(R.id.car_error_right_listView);
        rightListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent1 = new Intent(getApplicationContext(), CarErrorPictureActivity.class);
                startActivity(intent1);
            }
        });
    }

    public void sendData1() {       //车牌号、违章代码、地址、违章日期
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = RequestBody.create(MediaType.parse("app/json"),
                            "{\"UserName\":\"user1\"}");
                    Request request = new Request.Builder()
                            .url("http://192.168.1.102:8088/transportservice/action/GetAllCarPeccancy.do")
                            .post(requestBody)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    //数据解析
                    parseData1(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    //解析Data1数据
    public void parseData1(String jsonData) {
        Gson gson = new Gson();
        CarErrorResultInfo info = gson.fromJson(jsonData, CarErrorResultInfo.class);
        data1List = new ArrayList<>();
        data1List = info.getData1();
        sendData2();
    }

    public void sendData2() {       //违章代码、罚金、扣分、备注
        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody = RequestBody.create(MediaType.parse("app/json"),
                    "{\"UserName\":\"user1\"}");
            Request request = new Request.Builder()
                    .url("http://192.168.1.102:8088/transportservice/action/GetPeccancyType.do")
                    .post(requestBody)
                    .build();
            Response response = client.newCall(request).execute();
            String responseData = response.body().string();
            //数据解析
            parseData2(responseData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void parseData2(String jsonData) {
        Gson gson = new Gson();
        CarErrorResultInfo2 info2 = gson.fromJson(jsonData, CarErrorResultInfo2.class);
        List<Data2> data2List = new ArrayList<>();
        data2List = info2.getData2();
        int number = 0;
        int marks = 0;
        int penalty = 0;
        for (Data1 data1 : data1List) {
            if ((data1.getCarnumber().equals(carNumber))) {
                for (Data2 data2 : data2List) {
                    if ((data2.getPcode()).equals(data1.getPcode())) {
                        number++;   //未处理违章次数
                        marks = marks + data2.getPscore();  //总扣分
                        penalty = penalty + data2.getPmoney();  //总罚款
                        //给违章详情表存储数据
                        SQLiteDatabase db = carErrorResultDatabase.getWritableDatabase();
                        ContentValues values = new ContentValues();
                        values.put("carnumber", carNumber);
                        values.put("time", data1.getPdatetime());
                        values.put("address", data1.getPaddr());
                        values.put("remark", data2.getPremarks());
                        values.put("marks", data2.getPscore());
                        values.put("penalty", data2.getPmoney());
                        db.insert("CarErrorRight", null, values);
                    }
                }
            }
        }
        //给汽车资料卡片表存储数据
        SQLiteDatabase db = carErrorResultDatabase.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("carnumber", carNumber);
        values.put("number", number);
        values.put("marks", marks);
        values.put("penalty", penalty);
        db.insert("CarErrorLeft", null, values);
        //给ListView添加适配器
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CarErrorResultLeftAdapter leftAdapter = new CarErrorResultLeftAdapter();
                CarErrorResultRightAdapter rightAdapter = new CarErrorResultRightAdapter();
                leftListView.setAdapter(leftAdapter);
                rightListView.setAdapter(rightAdapter);
            }
        });
    }

    //LeftListView适配器
    private class CarErrorResultLeftAdapter extends BaseAdapter{

        private final List<LeftData> leftDataList;
        private final SQLiteDatabase db;

        public CarErrorResultLeftAdapter() {
            super();
            leftDataList = new ArrayList<>();
            //初始化数据库
            db = carErrorResultDatabase.getWritableDatabase();
            Cursor cursor = db.query("CarErrorLeft", null, null, null, null, null, null);
            //将数据遍历出来存入List集合中
            if (cursor.moveToFirst()) {
                do {
                    LeftData leftData = new LeftData();
                    leftData.setCarnumber(cursor.getString(cursor.getColumnIndex("carnumber")));
                    leftData.setNumber(cursor.getInt(cursor.getColumnIndex("number")));
                    leftData.setMarks(cursor.getInt(cursor.getColumnIndex("marks")));
                    leftData.setPenalty(cursor.getInt(cursor.getColumnIndex("penalty")));
                    leftDataList.add(leftData);
                }while (cursor.moveToNext());
            }
            cursor.close();
        }

        @Override
        public int getCount() {
            return leftDataList.size();
        }

        @Override
        public Object getItem(int position) {
            return leftDataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(CarErrorResultActivity.this, R.layout.car_error_result_left_item, null);
            TextView tvCarNumber = view.findViewById(R.id.left_item_carnumber);
            TextView tvNumber = view.findViewById(R.id.left_item_number);
            TextView tvMarks = view.findViewById(R.id.left_item_marks);
            TextView tvPenalty = view.findViewById(R.id.left_item_penalty);
            tvCarNumber.setText(leftDataList.get(position).getCarnumber());
            tvNumber.setText(leftDataList.get(position).getNumber()+"");
            tvMarks.setText(leftDataList.get(position).getMarks()+"");
            tvPenalty.setText(leftDataList.get(position).getPenalty()+"");
            ImageView imageView = view.findViewById(R.id.left_item_button);
            imageView.setTag(position);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //删除表中车牌号等于被点击item车牌号的一行数据
                    db.delete("CarErrorLeft", "carnumber == ?", new String[]{tvCarNumber.getText().toString()});
                    db.delete("CarErrorRight", "carnumber == ?", new String[]{tvCarNumber.getText().toString()});
                    CarErrorResultLeftAdapter leftAdapter = new CarErrorResultLeftAdapter();
                    CarErrorResultRightAdapter rightAdapter = new CarErrorResultRightAdapter();
                    leftListView.setAdapter(leftAdapter);
                    rightListView.setAdapter(rightAdapter);
                }
            });
            return view;
        }

    }
    //RightListView适配器
    private class CarErrorResultRightAdapter extends BaseAdapter{

        private final List<RightData> rightDataList;

        public CarErrorResultRightAdapter(){
            super();
            rightDataList = new ArrayList<>();
            //初始化数据库
            SQLiteDatabase db = carErrorResultDatabase.getWritableDatabase();
            Cursor cursor = db.query("CarErrorRight", null, null, null, null, null, null);
            if (cursor.moveToFirst()) {
                do {
                    RightData rightData = new RightData();
                    rightData.setTimes(cursor.getString(cursor.getColumnIndex("time")));
                    rightData.setAddress(cursor.getString(cursor.getColumnIndex("address")));
                    rightData.setRemark(cursor.getString(cursor.getColumnIndex("remark")));
                    rightData.setMarks(cursor.getInt(cursor.getColumnIndex("marks")));
                    rightData.setPenalty(cursor.getInt(cursor.getColumnIndex("penalty")));
                    rightDataList.add(rightData);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }

        @Override
        public int getCount() {
            return rightDataList.size();
        }

        @Override
        public Object getItem(int position) {
            return rightDataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(CarErrorResultActivity.this, R.layout.car_error_result_right_item, null);
            TextView tvTime = view.findViewById(R.id.right_item_time);
            TextView tvAddress = view.findViewById(R.id.right_item_address);
            TextView tvRemark = view.findViewById(R.id.right_item_remark);
            TextView tvMarks = view.findViewById(R.id.right_item_marks);
            TextView tvPenalty = view.findViewById(R.id.right_item_penalty);
            tvTime.setText(rightDataList.get(position).getTimes());
            tvAddress.setText(rightDataList.get(position).getAddress());
            tvRemark.setText(rightDataList.get(position).getRemark());
            tvMarks.setText(rightDataList.get(position).getMarks()+"");
            tvPenalty.setText(rightDataList.get(position).getPenalty()+"");
            return view;
        }
    }

    //如果活动不可见就直接杀掉
    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_car_error_result;
    }
}
